import React, { useRef, useEffect } from 'react';
import ReactECharts from 'echarts-for-react';
import ChartCard from './ChartCard';

interface LineChartData {
  name: string;
  data: number[];
  color?: string;
}

interface LineChartProps {
  title: string;
  subtitle?: string;
  data: LineChartData[];
  xAxisData: string[];
  loading?: boolean;
  height?: number;
  smooth?: boolean;
  showArea?: boolean;
  showGrid?: boolean;
  showLegend?: boolean;
  onRefresh?: () => void;
  className?: string;
  style?: React.CSSProperties;
}

export default function LineChart({
  title,
  subtitle,
  data,
  xAxisData,
  loading = false,
  height = 300,
  smooth = true,
  showArea = false,
  showGrid = true,
  showLegend = true,
  onRefresh,
  className,
  style
}: LineChartProps) {
  const chartRef = useRef<any>(null);

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      show: showLegend,
      data: data.map(item => item.name),
      bottom: 0
    },
    grid: {
      show: showGrid,
      left: '3%',
      right: '4%',
      bottom: showLegend ? '15%' : '3%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxisData,
      axisLine: {
        lineStyle: {
          color: '#e8e8e8'
        }
      },
      axisLabel: {
        color: '#666'
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#e8e8e8'
        }
      },
      axisLabel: {
        color: '#666'
      },
      splitLine: {
        lineStyle: {
          color: '#f0f0f0'
        }
      }
    },
    series: data.map((item, index) => ({
      name: item.name,
      type: 'line',
      smooth,
      data: item.data,
      lineStyle: {
        color: item.color || `hsl(${index * 60}, 70%, 50%)`
      },
      itemStyle: {
        color: item.color || `hsl(${index * 60}, 70%, 50%)`
      },
      areaStyle: showArea ? {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0,
            color: item.color || `hsla(${index * 60}, 70%, 50%, 0.3)`
          }, {
            offset: 1,
            color: item.color || `hsla(${index * 60}, 70%, 50%, 0.1)`
          }]
        }
      } : undefined
    }))
  };

  const handleExport = () => {
    if (chartRef.current) {
      const echartsInstance = chartRef.current.getEchartsInstance();
      const base64 = echartsInstance.getDataURL({
        type: 'png',
        pixelRatio: 2,
        backgroundColor: '#fff'
      });
      
      // 创建下载链接
      const link = document.createElement('a');
      link.download = `${title}-${new Date().toISOString().split('T')[0]}.png`;
      link.href = base64;
      link.click();
    }
  };

  const handleFullscreen = () => {
    if (chartRef.current) {
      const echartsInstance = chartRef.current.getEchartsInstance();
      const base64 = echartsInstance.getDataURL({
        type: 'png',
        pixelRatio: 2,
        backgroundColor: '#fff'
      });
      
      // 在新窗口中显示图表
      const newWindow = window.open('', '_blank');
      if (newWindow) {
        newWindow.document.write(`
          <html>
            <head><title>${title}</title></head>
            <body style="margin:0;padding:20px;text-align:center;">
              <h2>${title}</h2>
              <img src="${base64}" style="max-width:100%;height:auto;" />
            </body>
          </html>
        `);
      }
    }
  };

  return (
    <ChartCard
      title={title}
      subtitle={subtitle}
      loading={loading}
      onRefresh={onRefresh}
      onExport={handleExport}
      onFullscreen={handleFullscreen}
      className={className}
      style={style}
    >
      <ReactECharts
        ref={chartRef}
        option={option}
        style={{ height: `${height}px`, width: '100%' }}
        notMerge={true}
        lazyUpdate={true}
      />
    </ChartCard>
  );
}

// 导出类型
export type { LineChartProps, LineChartData };